﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;
using System.Globalization;

namespace JM.JCY.SharePointComponent.JCYAlbum.ViewObjectAlbums
{
    public partial class ViewObjectAlbumsUserControl : UserControl, ICallbackEventHandler
    {
        static int PAGESIZE = JCYConstant.Pagination.ViewAllAlbumPageSize;
        private int currentPageIndex;
        public string lastIndex = "1";
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadApplicationContext();
                Session["AlbumDT"] = null;
                BindList(1, true);
                string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
                string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);



            }
        }

        private void LoadApplicationContext()
        {
            _staffId = 11;
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
            }

            if (ApplicationContext.Current.GetKeyValue("appType") != null)
            {
                appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
            }
            HiddenFieldWC.Value = "F";
            switch (appType)
            {
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                    appId = 0;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                    appId = _staffId;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    HiddenFieldWC.Value = "T";
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    HiddenFieldWC.Value = "T";
                    break;
            }
        }
        protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            //Label lblContext = (Label)e.Item.FindControl("lblContext");
            //Image imgContext = (Image)e.Item.FindControl("imgContext");
        }

        protected void BindList(int pageIndex, bool needRender)
        {
            PhotoAlbumSearchDataSet.T_UserDepartmentDataTable department = new PhotoAlbumSearchDataSet.T_UserDepartmentDataTable();
            if (ViewState["AlbumDT"] == null)
            {
                string AlbumType = string.Empty;

                string type = Request.QueryString["Type"];
                //int appid = Convert.ToInt32(Request.QueryString["appid"]);
                
                PhotoAlbumSearchDataSet.T_UserCommitteeDataTable committee = new PhotoAlbumSearchDataSet.T_UserCommitteeDataTable();
                using (PhotoAlbumProxy proxy = new PhotoAlbumProxy())
                {
                    if (type == "W")    //all public
                    {
                        lblTitle.Text = "所属部门的相册";
                        department = proxy.GetUserDepartmentByUserId(_staffId);

                    }
                    else if (type == "C")    //My Contributions
                    {
                        committee = proxy.GetUserCommitteeByUserId(_staffId);

                        lblTitle.Text = "所属专题小组的相册";
                        foreach (PhotoAlbumSearchDataSet.T_UserCommitteeRow row in committee)
                        {
                            PhotoAlbumSearchDataSet.T_UserDepartmentRow rw = department.NewT_UserDepartmentRow();
                            rw.DepartmentId = row.CommitteeId;
                            rw.DeptName = row.CommitteeName;
                            rw.appType = "C";
                            rw.UserId = row.UserId;
                            department.AddT_UserDepartmentRow(rw);
                        }

                    }

                    dlResult.DataSource = department;
                    dlResult.DataBind();


                    ViewState["AlbumDT"] = department;
                }
            }
            else
            {
                department = (PhotoAlbumSearchDataSet.T_UserDepartmentDataTable)ViewState["AlbumDT"];
            }

            //Calculate total page count
            int pages = (department.Rows.Count % PAGESIZE == 0) ? department.Rows.Count / PAGESIZE : (department.Rows.Count / PAGESIZE) + 1;
            lastIndex = pages.ToString();
            HiddenFieldPageNum.Value = pages.ToString();

            if (pageIndex > pages)
                pageIndex = pages;
            else if (pageIndex < 1)
                pageIndex = 1;
            int startId = (pageIndex - 1) * PAGESIZE;
            int endId = pageIndex * PAGESIZE - 1;

            DataRow[] rows = department.Select(string.Format("id>={0} and id<={1}", startId, endId));
            dlResult.DataSource = rows;
            dlResult.DataBind();
        }

        public string GetCallbackResult()
        {
            //Return the rebind datalist's content
            return RenderControl(dlResult);
        }

        //Realize ICallbackEventHandler member RaiseCallbackEvent
        public void RaiseCallbackEvent(string eventArgument)
        {
            currentPageIndex = Convert.ToInt32(eventArgument);
            BindList(currentPageIndex, false);
        }

        private string RenderControl(Control control)
        {
            StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

            control.RenderControl(writer2);
            writer2.Flush();
            writer2.Close();

            return writer1.ToString();
        }

        public string PartSubString(string fieldName, string fieldValue)
        {
            return fieldValue;
        }
    }
}
